<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 商品分类级联框 -->
          <el-cascader
            v-model="selectedKey"
            :options="catelist"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addParam"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  class="tableExpandTag"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 新增标签的按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParam(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParam(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addParam"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开行 -->
                        <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  class="tableExpandTag"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 新增标签的按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParam(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParam(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamDialogVisible"
      width="50%"
      @close="addParamDialogClosed"
    >
      <el-form
        :model="addParamForm"
        :rules="addParamFormRules"
        ref="addParamFormRef"
        label-width="80px"
      >
        <!-- 添加参数内容主体区域 -->
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editParamDialogVisible"
      width="50%"
      @close="editParamDialogClosed"
    >
      <el-form
        :model="editParamInfo"
        :rules="editParamFormRules"
        ref="addParamFormRef"
        label-width="80px"
      >
        <!-- 修改参数内容主体区域 -->
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamInfo.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      catelist: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      //选中的分类的ID
      selectedKey: [],
      //被激活的页签的名称
      activeName: 'many',
      //静态参数的数据
      onlyTabData: [],
      //动态参数的数据
      manyTabData: [],
      //控制添加参数/属性对话框的显示隐藏
      addParamDialogVisible: false,
      //添加参数的数据
      addParamForm: {
        attr_name: '',
        id: '',
        attr_sel: '',
      },
      //编辑参数的数据
      editParamInfo: {
        id: '',
        attrId: '',
        attr_name: '',
        attr_sel: '',
      },
      //删除的参数的数据
      deleteParamInfo: {
        id: '',
        attrId: '',
      },
      //控制修改参数对话框的显示隐藏
      editParamDialogVisible: false,
      //添加参数规范
      addParamFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      //编辑参数规范
      editParamFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      this.catelist = res.data
    },
    //获取选中分类对应参数
    async getParamsData() {
      //判断：如果selectedKey的length大于0，则证明选中了分类
      //然后根据所选择的三级分类ID获取对应参数
      if (this.selectedKey.length === 0) {
        this.manyTabData = []
        this.onlyTabData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数数据失败')
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      }
      this.onlyTabData = res.data
    },
    //监听级联选择器的变化
    handleChange() {
      this.getParamsData()
    },
    //tab标签点击事件处理函数
    handleClick() {
      this.getParamsData()
    },
    //添加动态参数/静态属性的点击事件
    addParam() {
      this.addParamDialogVisible = true
      this.addParamForm.id = this.selectedKey[this.selectedKey.length - 1]
      this.addParamForm.attr_sel = this.activeName
    },
    //监听修改参数对话框关闭后的重置事件
    addParamDialogClosed() {
      this.$refs.addParamFormRef.resetFields()
    },
    //点击确认按钮，添加参数
    async addParamData() {
      //如果没有选中分类则清空table
      const { data: res } = await this.$http.post(
        `categories/${this.addParamForm.id}/attributes`,
        {
          attr_name: this.addParamForm.attr_name,
          attr_sel: this.addParamForm.attr_sel,
        }
      )
      if (res.meta.status !== 201) return this.$message.error('更新参数失败')
      this.$message.success('更新参数成功')
      this.getParamsData()
      this.addParamDialogVisible = false
    },
    //编辑参数对话框的点击事件
    editParam(param) {
      this.editParamDialogVisible = true
      console.log(param)
      this.editParamInfo.id = param.cat_id
      this.editParamInfo.attrId = param.attr_id
      this.editParamInfo.attr_name = param.attr_name
      this.editParamInfo.attr_sel = param.attr_sel
    },
    //编辑参数对话框的关闭事件
    editParamDialogClosed() {
      this.$refs.addParamFormRef.resetFields()
    },
    //点击确认，保存编辑的参数信息
    async editParamData() {
      const { data: res } = await this.$http.put(
        `categories/${this.editParamInfo.id}/attributes/${this.editParamInfo.attrId}`,
        {
          attr_name: this.editParamInfo.attr_name,
          attr_sel: this.editParamInfo.attr_sel,
        }
      )
      if (res.meta.status !== 200) return this.$message.error('更新参数失败')
      this.$message.success('更新参数成功')
      this.getParamsData()
      this.editParamDialogVisible = false
    },
    //删除指定的参数
    async removeParam(param) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return
      const { data: res } = await this.$http.delete(
        `categories/${param.cat_id}/attributes/${param.attr_id}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getParamsData()
    },
    //文本框失去焦点或按回车键触发事件
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveTagData(row)
    },
    //将添加或删除的参数标签保存到后台
    async saveTagData(row) {
      //需要发起请求保存
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) return this.$message.error('更新参数失败')
      this.$message.success('更新参数成功')
    },
    //点击添加标签按钮，打开输入框
    showInput(row) {
      row.inputVisible = true
      //让文本框自动获得焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除指定参数标签
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveTagData(row)
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedKey.length == 0) {
        return true
      }
      return false
    },
    //选择的三级分类的id
    cateId() {
      if (this.selectedKey.length !== 0) {
        return this.selectedKey[this.selectedKey.length - 1]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.tableExpandTag {
  margin: 5px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>